//
//  AddUserView.m
//  TaiHao
//
//  Created by rzm on 16/6/3.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxAddUserView.h"
#import "IsValidateOrNot.h"
#import "SampuxCustomTextFiledView.h"
#import "SPDeleteTextFiledView.h"

@interface SampuxAddUserView ()<UITextFieldDelegate>
{
    NSArray  *_arr;
}
@property (nonatomic, strong)  UITextField *nameF ;
@property (nonatomic, strong) UITextField *teleF ;
@property (nonatomic, strong) SPDeleteTextFiledView *teleView;
@property (nonatomic, strong) SPDeleteTextFiledView *nameView;
@property (nonatomic, strong) UIView *backView;

@end
@implementation SampuxAddUserView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addUser:) name:NOTIFICATION_RESPONSE_ADD_DEVICE_USER object:nil];
        self.backgroundColor = THSystemClearColor;
        _userArr = [NSMutableArray array];
        [self loadUI];

    }
    return self;
}

- (void)loadUI
{
    
    CGFloat font = 8.;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 17.;
    }else
    {
        font = 17.;
    }
    UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self addSubview:view];
    view.backgroundColor = THBlackAlplaColor(0.6);
    view.alpha = 1;
    
    _backView = [[UIView alloc]initWithFrame:CGRectMake(self.width *0.08, self.height * 0.3, self.width*0.84 ,self.height * 0.4)];
    [self addSubview:_backView];
    _backView.backgroundColor = [UIColor colorWithHex:0xff9a9a9b];
    [_backView setCorner:5];
    
    
    UILabel *lab = [UILabel createLabelWithText:@"添加使用者" frame:CGRectMake(0, 0, _backView.width, _backView.height * 0.15) font:THFont(font)];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.textColor = THSystemWhiteColor;
    [_backView addSubview:lab];
    lab.backgroundColor = THDeFaultBlueColor;
//    CGRectMake(self.width/2 - Sampux6WScale(SampuxCustomW)/2 , CGRectGetMaxY(_phoneNumView.frame) + SampuxMargin,  Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH))
    
    _teleView = [[SPDeleteTextFiledView alloc]initWithFrame:CGRectMake(_backView.width/2 - Sampux6WScale(250)/2 , CGRectGetMaxY(lab.frame) + _backView.height * 0.1,  Sampux6WScale(250), Sampux6HScale(SampuxCustomH))];
    [_backView addSubview:_teleView];
    [_teleView createDeleteTextFiledWithPlaceholder:@"输入使用者的用户名" andLeftImage:@"make-user" andRightImage:@"delete"];
    _teleView.textFiled.delegate = self;
    
//    _teleF = [UITextField createTextFieldWithRect: CGRectMake(_backView.width/2 - Sampux6WScale(220)/2 , CGRectGetMaxY(lab.frame) + _backView.height * 0.1,  Sampux6WScale(220), Sampux6HScale(SampuxCustomH)) andPlaceholder:@"请输入接收方的用户名" andLeftImage:@"make-user"];
//    [backView addSubview:_teleF];
    
    _nameView = [[SPDeleteTextFiledView alloc]initWithFrame:CGRectMake(_backView.width/2 - Sampux6WScale(250)/2 , CGRectGetMaxY(_teleView.frame) + _backView.height * 0.1,  Sampux6WScale(250), Sampux6HScale(SampuxCustomH))];
    [_nameView createDeleteTextFiledWithPlaceholder:@"设置别名" andLeftImage:@"feedBackCode" andRightImage:@"delete"];
    [_backView addSubview:_nameView];
    _nameView.textFiled.delegate = self;

    UIButton *yesBtn = [UIButton createButtonWithTitle:@"确定" frame:CGRectMake(_backView.width*0.2, CGRectGetMaxY(_nameView.frame) + Sampux6HScale(20), _backView.width* 0.6, _backView.height * 0.15) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [_backView addSubview:yesBtn];
    yesBtn.layer.borderWidth = 1;
    yesBtn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    [yesBtn addTarget:self action:@selector(yesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [yesBtn setCorner: yesBtn.height/2];
    
    _backView.height = yesBtn.bottom + Sampux6HScale(20);
}

- (void)yesBtnClick
{
    BOOL isMobile = [IsValidateOrNot isValidateMobile:self.teleView.textFiled.text];
    BOOL isEmail = [IsValidateOrNot isValidateEmail:self.teleView.textFiled.text];
    if ([self.teleView.textFiled.text isEqualToString:@""]||self.teleView.textFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
    } else {
        if (!isMobile&&!isEmail)
        {
            [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
        } else {
            if ([self.nameView.textFiled.text isEqualToString:@""]||self.nameView.textFiled.text.length == 0)
            {
                self.nameView.textFiled.text = self.teleView.textFiled.text;
            }
            [GBInterMaster_CommForSystem requestAddDeviceUser:0 withDeviceAccount:self.model.deviceAccount withUserAccount:self.teleView.textFiled.text withUserAlias:self.nameView.textFiled.text];
        }
    }
}

- (void)removeView
{
     dispatch_async(dispatch_get_main_queue(), ^{
        self.teleView.textFiled.text = @"";
        self.nameView.textFiled.text = @"";
        [self removeFromSuperview];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //宣告一个UITouch的指标来存放事件触发时所撷取到的状态
    UITouch *touch = [[event allTouches] anyObject];
    CGFloat ly = [touch locationInView:  self.backView].y;
        if ( ly < 0 || ly > self.backView.height ) { //点标题栏也会消失，点其他地方捕捉不到了
        [self removeView];
    }
    [super touchesBegan:touches withEvent:event];
}
#pragma -mark 输入框代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    CGFloat keyboardHeight = 216.0f;
    self.frame = CGRectMake(0, -keyboardHeight/3 , self.width, self.height);
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (void)addUser:(NSNotification *)notification
{
    [SVProgressHUD dismiss];
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"addUser == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        [SVProgressHUD showSuccessWithStatus:@"添加使用者成功"];
        GBInterMaster_Bean_DeviceOperatorInfo *Info = [[GBInterMaster_Bean_DeviceOperatorInfo alloc]init];
        Info.userAccount = self.teleView.textFiled.text;
        Info.userAlias = self.nameView.textFiled.text;
//        [d setObject:self.teleView.textFiled.text forKey:@"telenumber"];
//        [d setObject:self.nameView.textFiled.text forKey:@"username"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"addUserSuccess" object:nil];
        [self.userArr addObject:Info];
        if (self.addUserDelegate && [self.addUserDelegate respondsToSelector:@selector(addUserViewYesBtnClick:)]) {
            [self.addUserDelegate addUserViewYesBtnClick:self.userArr];
            [self removeView];
        }
        [self.userArr removeAllObjects];
    }else
    {
        [SPResponseCodePrompt responseCodePrompt:responseCode];
        [SVProgressHUD showErrorWithStatus:@"添加使用者失败"];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
